import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'

Vue.use(VueRouter)

const routes = [
  /*  {
     path: '/',
     name: 'home',
     component:HomeView,
  
     children:[
       {
         path:'user',name:'User',component:()=>import('@/views/UserView.vue')
       },
       {path:'main',name:'Main',component:()=>import('@/views/MainView.vue')},
       {path:'file',name:'File',component:()=>import('@/views/FileView.vue')},
       {path:'role',name:'Role',component:()=>import('@/views/RoleView.vue')},
       {path:'menu',name:'menu',component:()=>import('@/views/MenuView.vue')}
     ]
   }, */
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/Register.vue')
  },
  {
    name:'404',
    path:"/404",
    component:()=>import('@/views/404.vue')
  }

]


const router = new VueRouter({
  routes
})


export const setRouters = () => {
  const storeMenu = localStorage.getItem("menus");//得到用户菜单
  if (storeMenu) {
    const manageMenu = {
      path: '/',
      name: 'Manage',
      redirect:'/main',
      component: HomeView,
      children:[{
        name:'person',path:'person',component:()=>import('@/views/Person.vue')
      }]
    }
  const menus=JSON.parse(storeMenu) //转换格式
    menus.forEach(item => {
        if(item.path){ //path 不为空
          let itemMenu={path:item.path.replace("/",""),name:item.name,component:()=>import('@/views/'+item.pagePath+'.vue')}
          manageMenu.children.push(itemMenu)
        }
        else if(item.children.length){
          item.children.forEach(item=>{
            if(item.path){
            let itemMenu={path:item.path.replace("/",""),name:item.name,component:()=>import('@/views/'+item.pagePath+'.vue')}
            manageMenu.children.push(itemMenu)
            }
          })
        }
    });
    //重置避免重复路由
    const currentRoutNames=router.getRoutes().map(v=>v.name)
    if(!currentRoutNames.includes('Manage')){
     //添加动态路由
     router.addRoute(manageMenu)
    }
  }
}
//前置守卫
router.beforeEach((to,from,next)=>{
  const storeMenu=localStorage.getItem("menus");
  //没找到路由
  if(!to.matched.length){
    //动态菜单路由存在
    if(storeMenu){
      next("/404")
   }
   //动态菜单路由不存在
   else{
     next("/login")
   }
  }
  next()

})
//重置使用
setRouters();
export default router
